package com.bradz.mytv;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

public class activityMediaPlayer extends Activity{
	private classNetworkHolder network = null;
	private VideoView myVideoView;
	private TextView errorText, mediaText;
	private LinearLayout textBox, errorBox;
	private applicationGlobalVars globals;
	private Handler handler = new Handler();
	private boolean transitioning;
	private static String TAG;
	View.OnTouchListener gestureListener;
	Context self;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_media_player);
	    self = this;
	    TAG = "myTV";
	    
	    RelativeLayout lowestLayout = (RelativeLayout)this.findViewById(R.id.media_player_frame);
	    lowestLayout.setOnTouchListener(new OnSwipeTouchListener());
	    
	    errorBox = (LinearLayout) findViewById(R.id.error_text_layout);
		textBox = (LinearLayout) findViewById(R.id.media_text_layout);
		errorText = (TextView) findViewById(R.id.error_text);
		mediaText = (TextView) findViewById(R.id.media_text);
		Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-Book.otf");
		errorText.setTypeface(font);
		errorText.setSelected(true);
		mediaText.setTypeface(font);
	    globals = ((applicationGlobalVars) this.getApplication());
	    transitioning = false;
	    //someText = (TextView) findViewById(R.id.media_text);
	    new initialize_network_task().execute();
	}
	
	// We want to create a context Menu when the user long click on an item
	  @Override
	  public boolean onCreateOptionsMenu(Menu menu) {
	      ArrayList<String> channels = new ArrayList<String>(Arrays.asList(network.get_channel_names()));
	      ArrayList<String> shows = new ArrayList<String>(network.get_current_channel().get_channel_shows());
	      SubMenu channelMenu = menu.addSubMenu("Select Channel");
	      for(int i = 0; i < channels.size();i++){
	    	  channelMenu.add(3, i, i, channels.get(i));
	      }
	      SubMenu showMenu = menu.addSubMenu("Select Show");
	      for(int i = 0; i < shows.size();i++){
	    	  showMenu.add(2, i, i, shows.get(i));
	      }
	      return super.onPrepareOptionsMenu(menu);
	  }
	  
	  @Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		  int groupId = item.getGroupId();
	      int itemId = item.getItemId();
	      if (!item.hasSubMenu()){
	    	  Log.i("Settings Clicked - OnOptionsItemSelected",String.valueOf(itemId));
	    	  //User selected show from dropdown
		      if (groupId == 2 && itemId >=0){
			      network.get_current_channel().set_current_episode(network.get_current_channel().pick_random_episode(itemId,network.get_settings_holder().channel_scheduling));
				  network.get_current_channel().reset_episode_length();
				  network.get_current_channel().set_episode_offset(0);
				  load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
				  //Show the selected show after it is pulled from the menu
				  show_show_transition();
			  //User selected show from dropdown
		      }else if(groupId == 3 && itemId >=0){
		    	  load_media_player_task task = new load_media_player_task(itemId);
	        	  task.execute("custom");
		      }else{
		    	  switch(itemId){
		    	  	case -1:
		    	  		network.get_settings_holder().real_time = item.isChecked();
		    	  		break;
		    	  	case -2:
		    	  		network.get_settings_holder().channel_scheduling = item.isChecked();
		    	  		break;
		    	  	case -3:
		    	  		network.get_settings_holder().commercials = item.isChecked();
		    	  		break;
		    	  	case -4:
		    	  		network.get_settings_holder().show_errors = item.isChecked();
		    	  		break;
		    	  	case -5:
		    	  		break;
		    	  }
		    	  return true;
		      }
	      }
	    return false;
	  }
	
	public void set_things_up(){
		if(network.network_empty()){
	    	show_testing_message("You have no channels currently activiated. Set up your channels first, then start the network again.",true);
	    	finish();
	    }else{
	    	myVideoView = (VideoView)findViewById(R.id.media_player);
	    	set_player_actions();
	    	//If a path is corrupted, we need to reset the recovery table and try again... 
	    	try{
	    		network.load_last_episode();
	    		load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
	    	}catch(Exception e){
	    		network.reset_recovery_database();
	    		set_things_up();
	    	}
	    	show_channel_transition();
	    }
	}
	
	@Override
	public void onResume() {
		super.onResume();
		transitioning = false;
	    new initialize_network_task().execute();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		transitioning = false;
		save_network();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		transitioning = false;
		save_network();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		transitioning = false;
		save_network();
	}
	
	/*public void dispatch_event(){
		this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DPAD_RIGHT));
	}*/
	
	public void set_player_actions(){
		myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
	        @Override
	        public void onCompletion(MediaPlayer mp) {
	        	Log.i("mytv - On Completion Called", "mediaPlayer");
	        	network.get_current_channel().set_episode_offset(0);
	        	//show_testing_message("End of Episode: " + network.get_current_channel().get_current_episode());
	        	load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
	        }
	    });
	    myVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

	        public boolean onError(MediaPlayer mp, int what, int extra) {
	        	AlertDialog.Builder dialog = new AlertDialog.Builder(activityMediaPlayer.this);
                dialog.setTitle("Error");
                dialog.setMessage("Media File: " + network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()) + "\nIs not supported by Android. Please remove from folder in the future.");
	        	
                final AlertDialog dlg = dialog.create();
                
                if (network.get_settings_holder().show_errors){
                	dlg.show();
                }
                
                final Timer timer=new Timer();
                timer.schedule(new TimerTask() {
                    @Override  public void run() {  
                        dlg.dismiss();
                        timer.cancel();
                    }
                }, 7000);
	        	
                handler.removeCallbacksAndMessages(null);
                
                //Reset the top and bottom text_boxes if they exist
                errorBox.setAlpha(0);
  			  	textBox.setAlpha(0);
                
	            // TODO Auto-generated method stub
	        	network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling);
	        	network.save_last_episode();
	        	load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
	        	//Show the new show on the bottom now that we have reset the messages
	        	show_show_transition();

	            return true;
	        }

	    });
	    myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()  {
	    	 
            @Override
            public void onPrepared(MediaPlayer mp) { 
            		Log.i("mytv - episode prepared","mediaPlayer");
        			network.get_current_channel().set_episode_length(myVideoView.getDuration());
        			myVideoView.seekTo((int) network.get_current_channel().get_episode_offset() * 1000);
        			Log.i("mytv - episode seek to","mediaPlayer");
            		myVideoView.start();
            		Log.i("mytv - episode started","mediaPlayer");
                }

	    });
	}
	
	public void load_episode(final String episode){
		long offset = network.get_current_channel().get_offset() * 1000;
    	//This just sets the real time offset to 0 so that episodes stop when you stop watching them
    	if(!network.get_settings_holder().real_time){
    		offset = 0;
    	}
    	long episode_offset = network.get_current_channel().get_episode_offset() * 1000;
    	//This gives a 10% probability of there being a commercial in your future
    	network.roll_dice(10);
    	//Log.i("mytv - episode offset: " + episode_offset,"mediaPlayer");
    	//Log.i("mytv - network offset: " + offset,"mediaPlayer");
    	//Log.i("mytv - episode length: " + network.get_current_channel().get_episode_length(),"mediaPlayer");
    	//If the current episode has no length or the offset is less than the current episode's length
    	
    	//The offset calculation has to be here bc none of the media times are stored in the database. Just calculated when the media is played
    	
		if(network.get_current_channel().get_episode_length() <= 0 || 
				(network.get_current_channel().get_episode_length() > 0 && ((offset + episode_offset) < network.get_current_channel().get_episode_length()))){
			//Add the channel offset to the episode offset
			network.get_current_channel().set_episode_offset((long)((offset + episode_offset)/1000));
			//Reset the channel offset
			network.get_current_channel().reset_offset();
			if (!network.get_is_commercial()){
				myVideoView.setVideoPath(episode);
			}else{
				startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(network.return_commercial())));
				network.set_is_commercial(false);
				myVideoView.setVideoPath(episode);
			}
		    myVideoView.requestFocus();
		}else{
			network.get_current_channel().set_episode_offset(((offset + episode_offset) % network.get_current_channel().get_episode_length()) /1000);
			network.get_current_channel().reset_offset();
			
			load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
		}
	}
	
	public void show_show_transition(){
		show_testing_message(network.get_current_channel().get_show_name(),true);
	}
	
	public void show_channel_transition(){
		show_testing_message(network.get_current_channel().get_channel_name(),network.get_current_channel().get_show_name());
	}
	
	public void show_testing_message(String message, boolean error){
		//For some reason, null doesn't remove all of the handlers
		handler.removeCallbacksAndMessages(null);
		if (error){
			errorText.setText(message);
			errorBox.setAlpha(.8f);
			if (errorText.length() < 50){
				handler.postDelayed(runnable_error, 12000);
			}else{
				handler.postDelayed(runnable_error, 12000 + (errorText.length() - 50) * 150);
			}
		}else{
			mediaText.setText(message);
			textBox.setAlpha(.8f);
			if (mediaText.length() < 50){
				handler.postDelayed(runnable_text, 12000);
			}else{
				handler.postDelayed(runnable_text, 12000 + (mediaText.length() - 50) * 150);
			}
		}
	}
	
	public void show_testing_message(String text_message, String error_message){
		//For some reason, null doesn't remove all of the handlers
		handler.removeCallbacksAndMessages(null);
		errorText.setText(error_message);
		errorBox.setAlpha(.8f);
		if (errorText.length() < 50){
			handler.postDelayed(runnable_error, 12000);
		}else{
			handler.postDelayed(runnable_error, 12000 + (errorText.length() - 50) * 150);
		}
		mediaText.setText(text_message);
		textBox.setAlpha(.8f);
		if (mediaText.length() < 50){
			handler.postDelayed(runnable_text, 12000);
		}else{
			handler.postDelayed(runnable_text, 12000 + (mediaText.length() - 50) * 150);
		}
	}
	
	private Runnable runnable_text = new Runnable() {
		   @Override
		   public void run() {
		      /* do what you need to do */
			  errorBox.setAlpha(0);
			  textBox.setAlpha(0);
		   }
	};
	
	private Runnable runnable_error = new Runnable() {
		   @Override
		   public void run() {
		      /* do what you need to do */
			  errorBox.setAlpha(0);
			  textBox.setAlpha(0);
		   }
	};
	
	@Override
    /**
     * Overrides the callback method for a UI control handling a Movie
     **/
    public boolean onKeyDown(int keyCode, KeyEvent event) {

      /*
       * Chooses the action to take, based on the incoming keycode
       */
      switch (keyCode) {
            
        case KeyEvent.KEYCODE_DPAD_RIGHT:
        	Log.i("myTV - right clicked", "mediaPlayer");
        	if(myVideoView.isPlaying()){
        		load_media_player_task task = new load_media_player_task();
        		task.execute("right");
        		
        		/*network.get_current_channel().set_episode_offset(0);
        		load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
        		show_show_transition();*/
        	}
            return true;

        case KeyEvent.KEYCODE_DPAD_LEFT:
        	Log.i("myTV - left clicked", "mediaPlayer");
        	if(myVideoView.isPlaying()){
        		load_media_player_task task = new load_media_player_task();
        		task.execute("left");
        		
        		/*if(myVideoView.getCurrentPosition()>10000){
        			myVideoView.seekTo(0);
        		}else{
	        		network.get_current_channel().set_episode_offset(0);
	        		load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
	        		show_show_transition();
        		}*/
        	}
            return true;
            
        case KeyEvent.KEYCODE_DPAD_UP:
        	Log.i("myTV - up clicked", "mediaPlayer");
        	if(myVideoView.isPlaying()){
        		load_media_player_task task = new load_media_player_task();
        		task.execute("up");
        		
        		/*network.save_last_episode();
	        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
	        	network.move_up_channel();
	        	load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
	    	    show_channel_transition();*/
        	}
        	//invalidateOptionsMenu();
            return true;
            
        case KeyEvent.KEYCODE_DPAD_DOWN:
        	Log.i("myTV - down clicked", "mediaPlayer");
        	if(myVideoView.isPlaying()){
        		load_media_player_task task = new load_media_player_task();
        		task.execute("down");
        		
        		/*network.save_last_episode();
	        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
	        	network.move_down_channel();
	        	load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
	    	    show_channel_transition();*/
        	}
        	//invalidateOptionsMenu();
            return true;
        case KeyEvent.KEYCODE_R:
        	show_testing_message("Real Time: " + String.valueOf(network.get_settings_holder().real_time),true);
        	return true;
        case KeyEvent.KEYCODE_BACK:
        	save_network();
            return super.onKeyDown(keyCode, event);
        case KeyEvent.KEYCODE_ENTER:
        	print_episode();
            return true;
        case KeyEvent.KEYCODE_E:
        	show_testing_message("Elapsed Time Since Last Change: " + network.get_current_time(),true);
            return true;
        case KeyEvent.KEYCODE_O:
        	print_offset();
            return true;
            
        case KeyEvent.KEYCODE_L:
        	network.get_current_channel().switch_show_lock();
        	if(network.get_current_channel().get_show_lock()){
        		show_testing_message("Lock On",true);
        	}else{
        		show_testing_message("Lock Off",true);
        	}
            return true;
            
        case KeyEvent.KEYCODE_MEDIA_PAUSE:
        	if(myVideoView.isPlaying()){
        		myVideoView.pause();
        	}else{
        		myVideoView.start();
        	}
            return true;
        
        //This resyncs the sound with the video
        case KeyEvent.KEYCODE_DPAD_CENTER:
        	myVideoView.seekTo(myVideoView.getCurrentPosition());
        	return true;
            
        case KeyEvent.KEYCODE_MEDIA_PLAY:
        	myVideoView.start();
            return true;
            
        case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
        	myVideoView.seekTo(myVideoView.getCurrentPosition()+20000);
            return true;
            
        case KeyEvent.KEYCODE_MEDIA_REWIND: 
        	myVideoView.seekTo(myVideoView.getCurrentPosition()-10000);
            return true;
        /*
         * Keycodes should always be passed upwards in the chain for handling.
         */
        default:
          return super.onKeyDown(keyCode, event);
      }
    }
	
	public void print_offset(){
		long episode_offset = network.get_current_channel().get_episode_offset() * 1000;
    	long media_duration = myVideoView.getDuration();
    	String offset_text = "Current Position: " + myVideoView.getCurrentPosition() + "\t Channel Offset: " + episode_offset + "\t Media Duration: " + media_duration;
    	show_testing_message(offset_text,true);
	}
	
	public void print_episode(){
		String channel_text = network.get_current_channel().get_channel_name()+":\t\t";
		channel_text += network.get_current_channel().get_show_name() + "\t";
		channel_text += network.get_current_channel().get_episode_name();
		//channel_text += "Commercial: " + network.return_commercial();
    	show_testing_message(channel_text,true);
	}
	
	public void print_shows(){
		String channel_text = network.get_current_channel().get_channel_name()+":\t\t";
    	for(int i =0; i < network.get_current_channel().get_all_paths().size(); i++){
    		String show_path = network.get_current_channel().get_all_paths().get(i);
    		show_path = show_path.substring(show_path.lastIndexOf('/')==-1?0:show_path.lastIndexOf("/")+1,show_path.length());
    		if (i!=network.get_current_channel().get_all_paths().size() -1){
    			channel_text += show_path + ",\t";
    		}else{
    			channel_text += show_path;
    		}
    	}
    	show_testing_message(channel_text,true);
	}

	private class initialize_network_task extends AsyncTask<Void, Void, Void> {

		@Override
        protected void onPreExecute() {
			show_testing_message("Loading...",true);
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
            while (!globals.get_network_loaded()) {
           	 //Log.i("CurrentChannel - Thread",String.valueOf(network.not_initialized));
            }
            network = globals.get_network_object();
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void v) {
	    	set_things_up();
	    }
	}
	
	//This is the gesture control for the phone controls
	public class OnSwipeTouchListener implements OnTouchListener {

	    private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());

	    public boolean onTouch(final View view, final MotionEvent motionEvent) {
	        return gestureDetector.onTouchEvent(motionEvent);
	    }

	    private final class GestureListener extends SimpleOnGestureListener {

	    	private final ViewConfiguration vc = ViewConfiguration.get(self);
			private final int SWIPE_THRESHOLD = vc.getScaledPagingTouchSlop();
		    private final int SWIPE_VELOCITY_THRESHOLD = vc.getScaledMinimumFlingVelocity();

	        @Override
	        public boolean onDown(MotionEvent e) {
	        	Log.i(TAG + " down", "swiper");
	            return true;
	        }
	        
	        @Override
            public boolean onDoubleTap(MotionEvent e) {
              Log.i(TAG + " double_tap", "onDoubleTap");
              onTwoTaps();
              return super.onDoubleTap(e);
            }

	        @Override
	        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        	Log.i(TAG + " fling", "swiper");
	            boolean result = false;
	            try {
	                float diffY = e2.getY() - e1.getY();
	                float diffX = e2.getX() - e1.getX();
	                if (Math.abs(diffX) > Math.abs(diffY)) {
	                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
	                        if (diffX > 0) {
	                            onSwipeRight();
	                        } else {
	                            onSwipeLeft();
	                        }
	                    }
	                } else {
	                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
	                        if (diffY > 0) {
	                            onSwipeBottom();
	                        } else {
	                            onSwipeTop();
	                        }
	                    }
	                }
	            } catch (Exception exception) {
	                exception.printStackTrace();
	            }
	            return result;
	        }
	    }
	    
	    public void onTwoTaps() {
	    	Log.i(TAG + " double tap", "swiper");
	    	if(myVideoView.isPlaying()){
        		myVideoView.pause();
        	}else{
        		myVideoView.start();
        	}
	    }

	    public void onSwipeRight() {
	    	Log.i(TAG + " right swiped", "swiper");
	    	if(myVideoView.isPlaying()){
        		network.get_current_channel().set_episode_offset(0);
        		load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
        	}
	    }

	    public void onSwipeLeft() {
	    	Log.i(TAG + " left swiped", "swiper");
        	if(myVideoView.isPlaying()){
        		network.get_current_channel().set_episode_offset(0);
        		load_episode(network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling));
        	}
	    }

	    public void onSwipeTop() {
	    	Log.i(TAG + " up swiped", "mediaPlayer");
        	if(myVideoView.isPlaying()){
        		network.save_last_episode();
	        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
	        	network.move_up_channel();
	        	load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
	    	    show_channel_transition();
        	}
        	invalidateOptionsMenu();
	    }

	    public void onSwipeBottom() {
	    	Log.i(TAG + " down swiped", "swiper");
        	if(myVideoView.isPlaying()){
        		network.save_last_episode();
        		//Save the episode's current position in the channel class
	        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
	        	network.move_down_channel();
	        	load_episode(network.get_current_channel().get_episode(network.get_current_channel().get_current_episode()));
	    	    show_channel_transition();
        	}
        	invalidateOptionsMenu();
	    }
	}
	//Make sure that the network is active and working...
	private class load_media_player_task extends AsyncTask<String, Void, Void> {
		
		String action = "up";
		String episode = "";
		boolean reset_episode = false;
		int position = 0;
		
		load_media_player_task(){}
		
		load_media_player_task(int position){
			this.position = position;
		}
		
		@Override
        protected void onPreExecute() {
			
		}
		
		@Override
		protected Void doInBackground(String... arg0) {
			action = arg0[0];
			if(!transitioning){
				transitioning = true;
				if(action.equals("left")){
	        		if(myVideoView.getCurrentPosition()>10000){
	        			myVideoView.seekTo(0);
	        			reset_episode = true;
	        		}else{
		        		network.get_current_channel().set_episode_offset(0);
		        		episode = network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling);
	        		}
				}
				if(action.equals("right")){
	        		network.get_current_channel().set_episode_offset(0);
	        		episode = network.get_current_channel().get_random_episode(network.get_settings_holder().channel_scheduling);
				}
				if(action.equals("up")){
	        		network.save_last_episode();
		        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
		        	network.move_up_channel();
		        	episode = network.get_current_channel().get_episode(network.get_current_channel().get_current_episode());
				}
				if(action.equals("down")){
	        		network.save_last_episode();
		        	network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
		        	network.move_down_channel();
		        	episode = network.get_current_channel().get_episode(network.get_current_channel().get_current_episode());
				}
				if(action.equals("custom")){
					network.save_last_episode();
					network.get_current_channel().set_episode_offset(myVideoView.getCurrentPosition()/1000);
					network.set_current_channel(position);
					episode = network.get_current_channel().get_episode(network.get_current_channel().get_current_episode());
				}
			}
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void v) {
			if(action.equals("down") || action.equals("up") || action.equals("custom")){
				load_episode(episode);
	    	    show_channel_transition();
	        	invalidateOptionsMenu();
				save_network();
			}else{
				if(!reset_episode){
					load_episode(episode);
				}
				show_show_transition();
				save_network();
			}
			transitioning = false;
		}
	}
	
	public void save_network(){
		if(network != null && !network.network_empty()){
			network.save_last_episode();
		}
	}
}
